package org.example.volunteerend.service.impl;

import org.example.volunteerend.dto.UserLoginRequest;
import org.example.volunteerend.dto.UserRegisterRequest;
import org.example.volunteerend.entity.ProjectCategory;
import org.example.volunteerend.entity.User;
import org.example.volunteerend.mapper.ProjectCategoryMapper;
import org.example.volunteerend.mapper.UserInterestCategoryMapper;
import org.example.volunteerend.mapper.UserMapper;
import org.example.volunteerend.service.UserService;
import org.example.volunteerend.utils.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final JwtUtil jwtUtil;
    private final UserInterestCategoryMapper userInterestCategoryMapper;
    private final ProjectCategoryMapper projectCategoryMapper;

    public UserServiceImpl(
            UserMapper userMapper,
            JwtUtil jwtUtil,
            UserInterestCategoryMapper userInterestCategoryMapper,
            ProjectCategoryMapper projectCategoryMapper) {
        this.userMapper = userMapper;
        this.jwtUtil = jwtUtil;
        this.userInterestCategoryMapper = userInterestCategoryMapper;
        this.projectCategoryMapper = projectCategoryMapper;
    }

    @Override
    @Transactional
    public User register(UserRegisterRequest request) {
        // 检查用户名是否已存在
        if (userMapper.findByUsername(request.getUsername()) != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 转换请求对象为实体对象
        User user = new User();
        BeanUtils.copyProperties(request, user);

        // 插入用户数据
        userMapper.insert(user);
        return user;
    }

    @Override
    public Map<String, Object> login(UserLoginRequest request) {
        User user = userMapper.findByUsername(request.getUsername());
        if (user == null) {
            throw new RuntimeException("用户名不存在");
        }

        // 验证密码（注意：这里的密码已经在数据库中使用MD5加密）
        String encryptedPassword = org.springframework.util.DigestUtils
                .md5DigestAsHex(request.getPassword().getBytes());
        if (!user.getPassword().equals(encryptedPassword)) {
            throw new RuntimeException("密码错误");
        }

        // 生成token
        String token = jwtUtil.generateToken(user.getUserId());

        // 构建返回数据
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("user_id", user.getUserId());
        userInfo.put("username", user.getUsername());
        userInfo.put("real_name", user.getRealName());
        userInfo.put("avatar_url", user.getAvatarUrl());
        userInfo.put("is_admin", user.getIsAdmin());
        
        result.put("user_info", userInfo);
        return result;
    }

    @Override
    public User getUserInfo(Integer userId) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        return user;
    }

    @Override
    @Transactional
    public void updateUserInfo(Integer userId, User updateUser) {
        User existingUser = userMapper.findById(userId);
        if (existingUser == null) {
            throw new RuntimeException("用户不存在");
        }

        updateUser.setUserId(userId);
        userMapper.update(updateUser);
    }
    
    @Override
    @Transactional
    public void updateAvatar(Integer userId, String avatarUrl) {
        User existingUser = userMapper.findById(userId);
        if (existingUser == null) {
            throw new RuntimeException("用户不存在");
        }
        
        userMapper.updateAvatar(userId, avatarUrl);
    }
    
    @Override
    public List<ProjectCategory> getUserInterests(Integer userId) {
        // 验证用户是否存在
        User existingUser = userMapper.findById(userId);
        if (existingUser == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 获取用户感兴趣的分类
        return userInterestCategoryMapper.getUserInterestCategories(userId);
    }
    
    @Override
    @Transactional
    public void updateUserInterests(Integer userId, List<Integer> categoryIds) {
        // 验证用户是否存在
        User existingUser = userMapper.findById(userId);
        if (existingUser == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 验证分类是否存在
        if (categoryIds != null && !categoryIds.isEmpty()) {
            for (Integer categoryId : categoryIds) {
                ProjectCategory category = projectCategoryMapper.findById(categoryId);
                if (category == null) {
                    throw new RuntimeException("分类ID不存在: " + categoryId);
                }
            }
        }
        
        // 删除用户的所有兴趣分类
        userInterestCategoryMapper.deleteUserInterestCategories(userId);
        
        // 添加新的兴趣分类
        if (categoryIds != null && !categoryIds.isEmpty()) {
            for (Integer categoryId : categoryIds) {
                userInterestCategoryMapper.addUserInterestCategory(userId, categoryId);
            }
        }
    }
} 